import os


def EnsureFolders(path):
    # 去除首尾的空格
    path = path.strip()
    # 去除尾部 \ 符号
    path = path.rstrip("\\")
    isExists = os.path.exists(path)
    # 判断结果
    if not isExists:
        # 如果不存在则创建目录
        # 创建目录操作函数
        os.makedirs(path)
        # print(path+' 创建成功')
    return path


def NoDuplicateDbFile(filepath, filename):
    newFilename = filename
    oldFileList = []
    index = 1
    # 遍历
    for root, dirs, files in os.walk(filepath):
        # 获取文件名称及路径
        for file in files:
            file_path = os.path.join(root, file)
            file_name = os.path.basename(file_path)
            # value = file_name.find(newFilename)
            # # print(file_path, file_name, value)
            # if value != -1:
            oldFileList.append(file_name)
    print(filepath+filename+' <oldFileList>：', oldFileList)
    while index > 0:
        if newFilename in oldFileList:
            # 找到之后打印
            print('Get it', filepath + newFilename)
            newFilename = f"{filename[:-3]}_{index}.db"
            print('Create a new file：', newFilename)
            index += 1
        else:
            index = -1
    return filepath + newFilename


def NoDuplicateLogFile(filepath, filename):
    newFilename = filename
    oldFileList = []
    index = 1
    # 遍历
    for root, dirs, files in os.walk(filepath):
        # 获取文件名称及路径
        for file in files:
            file_path = os.path.join(root, file)
            file_name = os.path.basename(file_path)
            # value = file_name.find(newFilename)
            # # print(file_path, file_name, value)
            # if value != -1:
            oldFileList.append(file_name)
    print(filepath+filename+' <oldFileList>：', oldFileList)
    while index > 0:
        if newFilename in oldFileList:
            # 找到之后打印
            print('Get it', filepath + newFilename)
            newFilename = f"{filename[:-4]}_{index}.log"
            print('Create a new file：', newFilename)
            index += 1
        else:
            index = -1
    return filepath + newFilename


# 程序入口
if __name__ == "__main__":
    print(NoDuplicateDbFile('../data/records/', 'tempLog_08-31_23-27_BoevxaDb.db'))
